import 'dart:convert';
import 'package:grint/entity/user.dart';
import 'package:grint/utils/local_store.dart';

/// 用户数据管理工具类
/// 用于获取、修改和存储用户数据
class UserData {
  static final UserData _instance = UserData._internal();

  factory UserData() {
    return _instance;
  }

  UserData._internal();

  /// 获取所有用户
  Future<List<User>> getAllUsers() async {
    final localStore = LocalStore();

    // 获取用户数据JSON字符串
    final String usersJsonString = localStore.getTextValue(
      'users_data',
      defaultValue: '[]',
    );

    // 解析JSON字符串为用户列表
    List<dynamic> jsonList = jsonDecode(usersJsonString);
    return jsonList.map((json) => User.fromJson(json)).toList();
  }

  /// 通过ID获取单个用户
  Future<User?> getUserById(String userId) async {
    final localStore = LocalStore();

    // 获取用户数据
    final Map<String, dynamic>? userJson = localStore.getObjectValue(
      'user_$userId',
    );
    if (userJson == null) return null;

    return User.fromJson(userJson);
  }

  /// 通过用户名和密码验证用户
  Future<User?> validateUser(String username, String password) async {
    final users = await getAllUsers();

    // 查找匹配的用户
    for (var user in users) {
      if (user.username == username && user.password == password) {
        return user;
      }
    }

    return null;
  }

  /// 添加新用户
  Future<bool> addUser(User user) async {
    final localStore = LocalStore();

    // 获取现有用户
    List<User> users = await getAllUsers();

    // 检查用户名是否已存在
    bool exists = users.any((u) => u.username == user.username);
    if (exists) {
      return false;
    }

    // 添加新用户
    users.add(user);

    // 保存到本地存储
    final List<Map<String, dynamic>> usersJson =
        users.map((u) => u.toJson()).toList();
    final String usersJsonString = jsonEncode(usersJson);
    await localStore.setTextValue('users_data', usersJsonString);

    // 单独保存用户数据
    await localStore.setObjectValue('user_${user.id}', user.toJson());

    return true;
  }

  /// 更新用户信息
  Future<bool> updateUser(User user) async {
    final localStore = LocalStore();

    // 获取现有用户
    List<User> users = await getAllUsers();

    // 查找并更新用户
    int index = users.indexWhere((u) => u.id == user.id);
    if (index == -1) {
      return false;
    }

    users[index] = user;

    // 保存到本地存储
    final List<Map<String, dynamic>> usersJson =
        users.map((u) => u.toJson()).toList();
    final String usersJsonString = jsonEncode(usersJson);
    await localStore.setTextValue('users_data', usersJsonString);

    // 更新单独存储的用户数据
    await localStore.setObjectValue('user_${user.id}', user.toJson());

    return true;
  }

  /// 删除用户
  Future<bool> deleteUser(String userId) async {
    final localStore = LocalStore();

    // 获取现有用户
    List<User> users = await getAllUsers();

    // 查找并删除用户
    int initialLength = users.length;
    users.removeWhere((u) => u.id == userId);

    if (users.length == initialLength) {
      return false;
    }

    // 保存到本地存储
    final List<Map<String, dynamic>> usersJson =
        users.map((u) => u.toJson()).toList();
    final String usersJsonString = jsonEncode(usersJson);
    await localStore.setTextValue('users_data', usersJsonString);

    // 删除单独存储的用户数据
    await localStore.removeValue('user_$userId');

    return true;
  }
}
